package ualrcdg.shared;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


class CDGEntityResolver implements EntityResolver
{
	final private HashMap< String, File > dtdMap = new HashMap< String, File >( );

	/**
	 * Primary constructor
	 * 
	 * @param rootPath the base path at which the specified configuration file can be located, and to which the paths specified in that configuration file are relative 
	 * @param configFile the name of the configuration file which details the DTD lookup information for this CDGEntityResolver instance
	 * @throws FileNotFoundException If the specified configuration file cannot be located
	 * @throws IOException If an IO error occurs while the configuration file is being processed
	 */
	public CDGEntityResolver( String rootPath, String configFile ) throws FileNotFoundException, IOException
	{
		BufferedReader config = new BufferedReader( new FileReader( new File( rootPath + configFile ) ) );

		String dtdRootFolder = config.readLine( );
		String id = null;
		String dtdFilename = null;

		String dtdStorePath = rootPath + dtdRootFolder;

		while( ( id = config.readLine( ) ) != null && ( dtdFilename = config.readLine( ) ) != null )
		{
			dtdMap.put( id, new File( dtdStorePath + dtdFilename ) );
		}

		config.close( );
	}

	/*
	 * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String)
	 */
	@Override
	public InputSource resolveEntity( String publicId, String systemId ) throws SAXException, IOException
	{
		if( publicId != null )
		{
			throw new IllegalArgumentException( "CDGEntityResolver: cannot resolve PUBLIC[" + publicId + "]" );
		}

		File dtdFile = dtdMap.get( systemId );
		if( dtdFile == null )
		{
			throw new IOException( "CDGEntityResolver: Unable to resolve entity SYSTEM[" + systemId + "]" );
		}

		return new InputSource( new FileReader( dtdFile ) );
	}
}